package com.snsprj.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;

/**
 * @author SKH
 * @date 2018-10-31 10:31
 **/
public class EchoServer {

    private final int port;

    public EchoServer(int port){
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {

//        if (args.length != 1){
//
//            System.out.println("Usage: " + EchoServer.class.getSimpleName() + " <port>");
//        }

//        int port = Integer.parseInt(args[0]);

        int port = 8000;

        new EchoServer(port).start();
    }

    public void start() throws InterruptedException {

        final EchoServerHandler serverHandler = new EchoServerHandler();

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(serverHandler);
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            channelFuture.channel().closeFuture().sync();


        }finally {
            eventLoopGroup.shutdownGracefully().sync();
        }
    }
}
